// ==UserScript==
// @name         网页转二维码
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  将当前网页URL转换为二维码
// @author       Cursor
// @match        http://*/*
// @match        https://*/*
// @grant        GM_addStyle
// @grant        GM_registerMenuCommand
// @require      https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js
// @icon         https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/%E7%BD%91%E9%A1%B5%E8%BD%AC%E4%BA%8C%E7%BB%B4%E7%A0%81/Web-QR.png
// ==/UserScript==

(function() {
    'use strict';

    // 添加样式
    GM_addStyle(`
        #qrcode-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9998;
            display: none;
            justify-content: center;
            align-items: center;
        }
        #qrcode-container {
            position: relative;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0,0,0,0.3);
            z-index: 9999;
            text-align: center;
            width: 320px;
            margin: auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            max-height: 90vh;
            overflow-y: auto;
        }
        #qrcode-close {
            position: absolute;
            top: 10px;
            right: 10px;
            cursor: pointer;
            font-size: 20px;
            color: #666;
            width: 26px;
            height: 26px;
            line-height: 26px;
            text-align: center;
            border-radius: 50%;
        }
        #qrcode-close:hover {
            background: #f2f2f2;
        }
        #qrcode-title {
            margin: 0 0 15px 0;
            font-size: 16px;
            color: #333;
            font-weight: bold;
            width: 100%;
            text-align: center;
        }
        #qrcode {
            margin: 10px 0;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        #qrcode img {
            width: 200px;
            height: 200px;
            border: 1px solid #eee;
        }
        #qrcode p {
            max-width: 100%;
            word-break: break-all;
            margin-top: 10px;
            font-size: 12px;
            color: #666;
            padding: 0 10px;
        }
        #custom-url-container {
            width: 100%;
            margin: 10px 0;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        #custom-url-input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            font-size: 14px;
            box-sizing: border-box;
        }
        #custom-url-btn {
            width: 100%;
            background: #4285f4;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.2s;
        }
        #custom-url-btn:hover {
            background: #3367d6;
        }
        #qrcode-tab {
            display: flex;
            width: 100%;
            margin-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .qrcode-tab-item {
            flex: 1;
            padding: 8px 0;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            font-size: 14px;
            color: #666;
            text-align: center;
        }
        .qrcode-tab-item.active {
            color: #4285f4;
            border-bottom-color: #4285f4;
        }
        #close-btn-container {
            margin-top: 15px;
            width: 100%;
            display: flex;
            justify-content: center;
        }
        #close-btn {
            width: 100%;
            background: #f2f2f2;
            color: #333;
            border: none;
            padding: 8px 0;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.2s;
        }
        #close-btn:hover {
            background: #e0e0e0;
        }
        #custom-url-tip {
            color: #999;
            font-size: 12px;
            margin: 0 0 10px 0;
            text-align: center;
            width: 100%;
        }
        @media (max-width: 360px) {
            #qrcode-container {
                width: 280px;
                padding: 12px;
            }
            #qrcode img {
                width: 180px;
                height: 180px;
            }
            #qrcode-title {
                font-size: 14px;
                margin-bottom: 10px;
            }
        }
    `);

    // 创建背景遮罩和容器的函数
    function createQRCodeElements() {
        // 防止重复创建
        if (document.getElementById('qrcode-overlay')) {
            return;
        }
        
        // 创建背景遮罩
        const overlay = document.createElement('div');
        overlay.id = 'qrcode-overlay';
        
        // 创建二维码容器
        const container = document.createElement('div');
        container.id = 'qrcode-container';
        
        const title = document.createElement('p');
        title.id = 'qrcode-title';
        title.textContent = '二维码生成器';
        container.appendChild(title);
        
        const closeBtn = document.createElement('span');
        closeBtn.id = 'qrcode-close';
        closeBtn.textContent = '×';
        closeBtn.title = '关闭';
        container.appendChild(closeBtn);
        
        // 创建tab切换
        const tabContainer = document.createElement('div');
        tabContainer.id = 'qrcode-tab';
        
        const currentPageTab = document.createElement('div');
        currentPageTab.className = 'qrcode-tab-item active';
        currentPageTab.textContent = '当前网页';
        currentPageTab.dataset.tab = 'current';
        
        const customUrlTab = document.createElement('div');
        customUrlTab.className = 'qrcode-tab-item';
        customUrlTab.textContent = '自定义网址';
        customUrlTab.dataset.tab = 'custom';
        
        tabContainer.appendChild(currentPageTab);
        tabContainer.appendChild(customUrlTab);
        container.appendChild(tabContainer);
        
        const qrcodeElement = document.createElement('div');
        qrcodeElement.id = 'qrcode';
        container.appendChild(qrcodeElement);
        
        // 创建自定义URL输入区域
        const customUrlContainer = document.createElement('div');
        customUrlContainer.id = 'custom-url-container';
        customUrlContainer.style.display = 'none';
        
        const customUrlTip = document.createElement('p');
        customUrlTip.id = 'custom-url-tip';
        customUrlTip.textContent = '请在下方输入网址并点击生成';
        customUrlContainer.appendChild(customUrlTip);
        
        const customUrlInput = document.createElement('input');
        customUrlInput.id = 'custom-url-input';
        customUrlInput.type = 'text';
        customUrlInput.placeholder = '请输入网址，如 https://www.baidu.com';
        customUrlInput.value = 'https://';
        
        const customUrlBtn = document.createElement('button');
        customUrlBtn.id = 'custom-url-btn';
        customUrlBtn.textContent = '生成二维码';
        
        customUrlContainer.appendChild(customUrlInput);
        customUrlContainer.appendChild(customUrlBtn);
        container.appendChild(customUrlContainer);
        
        // 创建专门的关闭按钮
        const closeBtnContainer = document.createElement('div');
        closeBtnContainer.id = 'close-btn-container';
        
        const closeButton = document.createElement('button');
        closeButton.id = 'close-btn';
        closeButton.textContent = '关闭';
        closeButton.title = '关闭二维码';
        
        closeBtnContainer.appendChild(closeButton);
        container.appendChild(closeBtnContainer);
        
        overlay.appendChild(container);
        document.body.appendChild(overlay);
        
        // 点击关闭按钮隐藏二维码
        closeBtn.addEventListener('click', function() {
            overlay.style.display = 'none';
        });
        
        // 点击底部关闭按钮隐藏二维码
        closeButton.addEventListener('click', function() {
            overlay.style.display = 'none';
        });
        
        // 点击背景遮罩也可以关闭二维码，但必须确保点击的是遮罩本身
        overlay.addEventListener('click', function(e) {
            if (e.target === overlay) {
                overlay.style.display = 'none';
            }
        });
        
        // 添加TAB切换事件
        const tabItems = container.querySelectorAll('.qrcode-tab-item');
        tabItems.forEach(item => {
            item.addEventListener('click', function(e) {
                // 阻止事件冒泡
                e.stopPropagation();
                
                // 移除所有active类
                tabItems.forEach(tab => tab.classList.remove('active'));
                // 为当前点击的添加active类
                this.classList.add('active');
                
                // 显示/隐藏不同内容
                if (this.dataset.tab === 'current') {
                    generateQRCode(window.location.href);
                    customUrlContainer.style.display = 'none';
                } else {
                    customUrlContainer.style.display = 'flex';
                    qrcodeElement.innerHTML = '';
                }
            });
        });
        
        // 添加自定义URL生成按钮事件
        customUrlBtn.addEventListener('click', function(e) {
            // 阻止事件冒泡
            e.stopPropagation();
            
            const url = customUrlInput.value.trim();
            if (url && url !== 'https://') {
                generateQRCode(url);
            } else {
                qrcodeElement.innerHTML = '<p style="color:red;">请输入有效网址</p>';
            }
        });
        
        // 阻止输入框的点击事件冒泡到背景
        customUrlInput.addEventListener('click', function(e) {
            e.stopPropagation();
        });
        
        // 按回车也可以生成
        customUrlInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                customUrlBtn.click();
            }
        });
    }
    
    // 确保页面加载完毕后创建元素
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', createQRCodeElements);
    } else {
        createQRCodeElements();
    }
    
    // 生成二维码的通用函数
    function generateQRCode(url) {
        const qrcodeElement = document.getElementById('qrcode');
        if (!qrcodeElement) return;
        
        // 清空之前的二维码
        qrcodeElement.innerHTML = '';
        
        try {
            // 使用固定尺寸生成二维码
            QRCode.toDataURL(url, {
                width: 200,
                margin: 1,
                color: {
                    dark: '#000000',
                    light: '#ffffff'
                }
            }, function(error, dataURL) {
                if (error) {
                    console.error('生成二维码出错:', error);
                    qrcodeElement.textContent = '生成二维码失败: ' + error.message;
                } else {
                    // 创建图片元素并设置数据URL
                    const img = document.createElement('img');
                    img.src = dataURL;
                    img.alt = '网址二维码';
                    qrcodeElement.appendChild(img);
                    
                    // 添加显示当前网址的文本
                    const urlText = document.createElement('p');
                    urlText.textContent = url;
                    qrcodeElement.appendChild(urlText);
                }
            });
        } catch (e) {
            console.error('QRCode生成异常:', e);
            qrcodeElement.textContent = '生成二维码失败: ' + e.message;
        }
    }

    // 显示二维码函数
    function showQRCode() {
        // 确保元素已创建
        createQRCodeElements();
        
        const overlay = document.getElementById('qrcode-overlay');
        if (!overlay) {
            console.error('二维码元素未找到');
            return;
        }
        
        // 默认显示当前网页的二维码
        const currentTab = document.querySelector('.qrcode-tab-item[data-tab="current"]');
        if (currentTab) {
            currentTab.click();
        } else {
            generateQRCode(window.location.href);
        }
        
        // 显示遮罩
        overlay.style.display = 'flex';
    }

    // 注册暴力猴菜单命令
    GM_registerMenuCommand('显示二维码', showQRCode);
    
    // 添加按ESC键关闭功能
    document.addEventListener('keydown', function(e) {
        const overlay = document.getElementById('qrcode-overlay');
        if (e.key === 'Escape' && overlay && overlay.style.display === 'flex') {
            overlay.style.display = 'none';
        }
    });
})(); 